<template>
  <div>
    <el-tabs v-model="activeTab" @tab-click="handleClick">
      <el-tab-pane label="外部导入镜像" name="first">外部导入镜像</el-tab-pane>
      <el-tab-pane label="手动创建镜像" name="second">手动创建镜像</el-tab-pane>
    </el-tabs>
    <div class="form">
      <div class="demo-input-suffix">
        <span class="form-input-label">镜像名称：</span>
        <el-input v-model="data.image_name" placeholder="请输入名称"></el-input>
      </div>

      <div class="demo-input-suffix">
        <span class="form-input-label">镜像源格式：</span>
        <el-select v-model="data.image_type" placeholder="请选择">
          <el-option
            v-for="item in image_types"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div class="demo-input-suffix">
        <span class="form-input-label">镜像源：</span>
        <input type="file" style="margin-bottom: 10px;" @change="onUpload" name="image_sourse" id="file" />
        <el-progress v-if="uploading" :text-inside="true" :stroke-width="26" :percentage="uploadPercentage"></el-progress>
        {{speed}}
      </div>
      <div class="demo-input-suffix">
        <span class="form-input-label">操作系统：</span>
        <el-select v-model="data.operation_system" placeholder="请选择">
          <el-option
            v-for="item in os_types"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </div>
      <div class="demo-input-suffix">
        <span class="form-input-label">系统架构：</span>
        <el-select v-model="data.architecture" placeholder="请选择">
          <el-option
            v-for="item in arches"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </div>
      <div class="demo-input-suffix">
        <span class="form-input-label">系统平台：</span>
        <el-select v-model="data.platform" placeholder="请选择">
          <el-option
            v-for="item in os_types"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </div>
      <div class="demo-input-suffix">
        <span class="form-input-label">系统版本：</span>
        <el-select v-model="data.version" placeholder="请选择">
          <el-option
            v-for="item in os_versions[data.operation_system]"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </div>
    <div class="dialog-footer">
      <el-button type="primary" @click="onSubmit">保 存</el-button>
    </div>
    </div>
  </div>
</template>

<script>
import ImageTypes from '@/common/image_types.js'
// import {upload} from '@/api/http.js'
import {cosModel, imageModel} from '../api/models'
import {Message} from 'element-ui';
import ImageSelects from '../common/image_selects'
const COS = require('cos-js-sdk-v5');
export default {
  data() {
    return {
      activeTab: 'first',
      data: {
        image_name: '',
        image_type: null,
        image_source: null,
      },
      image_types: ImageTypes.types,
      arches: ImageSelects.arch,
      os_types: ImageSelects.os_types,
      os_versions: ImageSelects.os_versions,
      uploading: false,
      uploadPercentage: 0,
      speed: ''
    }
  },
  methods: {
    handleClick(tab) {
      if(tab.name === 'second') {
        this.$router.replace('/image/create1')
      }
    },
    onUpload(e) {
      console.log(e,event)
      this.data.image_source = event.target.files[0];
      let cos = new COS({
        getAuthorization: function (options, callback) {
          cosModel.getSTS((res) => {
            console.log(res)
            let data = res.data
            let credentials = data && data.credentials;
            if (!data || !credentials) return Message.warning('cos预签名失败')
            callback({
              TmpSecretId: credentials.tmpSecretId,
              TmpSecretKey: credentials.tmpSecretKey,
              XCosSecurityToken: credentials.sessionToken,
              // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
              StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
              ExpiredTime: data.expiredTime, // 时间戳，单位秒，如：1580000900
              // ScopeLimit: true, // 细粒度控制权限需要设为 true，会限制密钥只在相同请求时重复使用
            })
          })
        }
      });
      cos.sliceUploadFile({
        Bucket: 'os-image-bj-1258514725', /* 必须 */
        Region: 'ap-beijing',     /* 存储桶所在地域，必须字段 */
        Key: 'cvmobjects/' + e.target.files[0].name,              /* 必须 */
        Body: e.target.files[0],                /* 必须 */
        onTaskReady: (taskId) => {                   /* 非必须 */
          console.log('onTaskReady:', taskId);
        },
        onHashProgress: (progressData) => {       /* 非必须 */
          console.log('progras', progressData)
        },
        onProgress: (progressData) => {           /* 非必须 */
          console.log('onProgress', progressData)
          this.uploading = true
          this.uploadPercentage = parseInt(progressData.percent * 100)
          this.speed = (progressData.speed / 1024 / 1024).toFixed(2) + 'M/s'
        }
      }, (err, data) => {
          console.log(err || data);
          if (!err) {
            this.data.image_source = data.Key
            this.data.image_url = data.Key
          }
      });
    },
    onSubmit() {
      let file = document.getElementById('file')
      if(file.files.length == 0){
        return Message.warning('请选择镜像文件')
      }
      console.log(111111111111111)
      console.log(this.data.image_source)
      console.log(111111111111111)
      if(!this.data.image_source) {
        return Message.warning('镜像尚未上传完整')
      }
      if(!this.data.image_type || !this.data.image_name || !this.data.operation_system 
      || !this.data.architecture || !this.data.platform || !this.data.version) {
        return Message.warning('请填完整信息');
      }
      let d = this.data
      d.image_source = file.files[0].name
      imageModel.createImport(d, (res) => {
        Message.success(res.message)
        this.$router.go(-1)
      }, err => {
        console.log(err)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.form{
  text-align: left;
}
#image_source{
  height: 34px;
}
</style>